package dbutils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Test;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * commons dbutils
 * Created by kevin on 2020/4/2.
 */
public class Demo3 {
    @Test
    public void fun1(){
       QueryRunner qr= new QueryRunner(JdbcUtils.getDataSource());
        String sql="insert into stu values(?,?,?,?,?)";
        Object[] params = {"0003","李四",30,"男","111111"};
        try {
            qr.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void fun2(){
        QueryRunner qr= new QueryRunner(JdbcUtils.getDataSource());
        String sql="select * from stu where number=?";
        Object[] params = {"0003"};
        try {
//            ResultSetHandler<Stu> handler = new ResultSetHandler<Stu>() {
//                @Override
//                public Stu handle(ResultSet rs) throws SQLException {
//                    if(!rs.next())  return null;
//                    Stu stu = new Stu();
//                    stu.setNumber(rs.getString("number"));
//                    stu.setName(rs.getString("name"));
//                    stu.setAge(rs.getInt("age"));
//                    stu.setGender(rs.getString("gender"));
//                    stu.setPassword(rs.getString("password"));
//                    return stu;
//                }
//            };//该部分代码commons-dbutils已经有5个实现类了可以直接调用
            //BeanHandler类是ResultSetHandler实现类,BeanHandler类使用需知(数据库列名必须与实体类名称相同)
            BeanHandler<Stu> beanHandler = new BeanHandler<Stu>(Stu.class);
            Stu stu = qr.query(sql,beanHandler,params);
            System.out.println(stu.toString());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
